/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

const _ = require('lodash')
const path = require('path')

// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '..')
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')

// 引入辅助函数模块
const { getKillGroupAccuracy } = require(path.join(HELPERS_DIR, 'getKillGroupAccuracy.js'))
const { filterForecaArray } = require(path.join(HELPERS_DIR, 'filterForecaArray.js'))
const { getLuckAndForecastIds } = require(path.join(HELPERS_DIR, 'getLuckAndForecastIds.js'))

// 批量更新数据
const updateData = async (connection, calcData, update_table_name) => {
  try {
    // 构造批量更新 SQL 语句
    const updateQuery = `
      UPDATE ${update_table_name}
      SET
        red_continuous_limit_2_group_ids = ?,
        green_rebound_red_non_continuous_group_ids = ?,
        green_continuous_group_ids = ?,
        lucky_array = ?,
        kill_array = ?,
        accuracy = ?
      WHERE id = ?;
    `

    // 遍历 calcData，逐个更新
    for (const data of calcData) {
      // // 检查每个字段是否为 undefined 或不符合规范
      // const fieldsToCheck = [
      //   { name: 'id', value: data.id },
      //   { name: 'red_continuous_limit_2_group_ids', value: data.red_continuous_limit_2_group_ids },
      //   { name: 'green_rebound_red_non_continuous_group_ids', value: data.green_rebound_red_non_continuous_group_ids },
      //   { name: 'green_continuous_group_ids', value: data.green_continuous_group_ids },
      //   { name: 'lucky_array', value: data.lucky_array },
      //   { name: 'kill_array', value: data.kill_array },
      //   { name: 'accuracy', value: data.accuracy }
      // ]

      // // 打印不符合规范的字段
      // fieldsToCheck.forEach((field) => {
      //   if (field.value === undefined) {
      //     console.error(`字段 ${field.name} 的值为 undefined，记录 ID: ${data.id}`);
      //   } else if (field.name === 'accuracy' && typeof field.value !== 'number') {
      //     console.error(`字段 ${field.name} 的值不是数字，记录 ID: ${data.id}，当前值: ${field.value}`);
      //   } else if (field.name !== 'accuracy' && !Array.isArray(field.value)) {
      //     console.error(`字段 ${field.name} 的值不是数组，记录 ID: ${data.id}，当前值: ${field.value}`);
      //   }
      // });

      // 将 undefined 替换为 null
      const params = [
        data.red_continuous_limit_2_group_ids,
        data.green_rebound_red_non_continuous_group_ids,
        data.green_continuous_group_ids,
        data.lucky_array,
        data.kill_array,
        data.accuracy,
        data.id
      ]

      await connection.execute(updateQuery, params)
    }

    console.log('数据更新成功')
  } catch (error) {
    console.error('更新数据时出错:', error)
    throw error
  }
}

// 主逻辑：更新历史预测数据
const updateHistoryForecast = async (pool, history_results, read_table_name, update_table_name) => {
  let previousElement = null

  // 获取连接池的连接
  const connection = await pool.getConnection()

  // 开始事务
  await connection.beginTransaction()

  try {
    const updateDataArray = []

    for (const [index, element] of history_results.entries()) {
      if (index === 0) {
        console.log('element', element)
      }
      if (index < 2) {
        // 前两条数据，不进行计算
        updateDataArray.push({
          id: element.id, // 主键
          red_continuous_limit_2_group_ids: JSON.stringify([]),
          green_rebound_red_non_continuous_group_ids: JSON.stringify([]),
          green_continuous_group_ids: JSON.stringify([]),
          lucky_array: JSON.stringify([]),
          kill_array: JSON.stringify([]),
          accuracy: 1
        })
      } else {
        // 查询前一个元素的总结数据
        const [prevSummary] = await connection.query(`SELECT * FROM ${read_table_name} WHERE history_result_id = ?`, [
          previousElement.id
        ])

        // 计算准确率
        const { accuracy } = getKillGroupAccuracy(prevSummary, element.number)

        // 查询当前元素的总结数据
        const [currentSummary] = await connection.query(
          `SELECT * FROM ${read_table_name} WHERE history_result_id = ?`,
          [element.id]
        )

        // 过滤预测数组
        const { redContinuousLimit2Group, greenReboundRedNonContinuousGroup, greenContinuousGroup } =
          filterForecaArray(currentSummary)

        // 获取幸运和杀前组 ID
        const {
          kill_array,
          lucky_array,
          red_continuous_limit_2_group_ids,
          green_rebound_red_non_continuous_group_ids,
          green_continuous_group_ids
        } = getLuckAndForecastIds(redContinuousLimit2Group, greenReboundRedNonContinuousGroup, greenContinuousGroup)
        

        // 构造更新数据
        updateDataArray.push({
          id: element.id, // 主键
          red_continuous_limit_2_group_ids,
          green_rebound_red_non_continuous_group_ids,
          green_continuous_group_ids,
          lucky_array,
          kill_array,
          accuracy: index === 2 ? 1 : accuracy
        })
      }

      // 更新 previousElement 为当前元素
      previousElement = element
    }

    // 批量更新数据
    await updateData(connection, updateDataArray, update_table_name)

    // 提交事务
    await connection.commit()
    console.log('事务提交成功')
  } catch (err) {
    // 回滚事务
    await connection.rollback()
    console.error('处理过程中发生错误:', err)
  } finally {
    // 释放连接
    connection.release()
  }
}

module.exports = { updateHistoryForecast }
